﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace JX.Infrastructure.Common
{
	/// <summary>
	/// 二维码操作类
	/// </summary>
	public class QRCodeHelper
	{
		/// <summary>
		/// 生成二维码图片，返回图片地址。
		/// 1、生成二维码图片，并保存图片到本地。
		/// 2、返回图片地址。例：QRCode/202001011122334441234.jpg
		/// </summary>
		/// <param name="plainText">扫描二维码时显示的文本内容</param>
		/// <param name="pixel">像素大小</param>
		/// <param name="logoPath">图标路径(例：E:\logo.jpg)</param>
		/// <returns></returns>
		public static string CreateQRCode(string plainText, int pixel = 10, string logoPath = "")
		{
			string QRCodeDirName = Utility.UploadDirPath(true) + "QRCode/";
			string QRCodeFileName = DataSecurity.MakeFileRndName() + ".jpg";
			string QRCodeFilePath = QRCodeDirName + QRCodeFileName;
			if (!FileHelper.IsExist(QRCodeDirName, FileMethod.Folder))
			{
				FileHelper.CreateFileFolder(QRCodeDirName);
			}
			//生成二维码图片
			Bitmap bitmap = CreateQRCodeImage(plainText, pixel, logoPath);
			//保存图片到本地
			Image imageNew = new Bitmap(bitmap.Width, bitmap.Height);
			Graphics draw = Graphics.FromImage(imageNew);
			draw.DrawImage(bitmap, 0, 0);
			bitmap.Dispose();
			imageNew.Save(QRCodeFilePath, ImageFormat.Jpeg);
			return "QRCode/" + QRCodeFileName;
		}

		/// <summary>
		/// 生成二维码图片
		/// </summary>
		/// <param name="plainText">扫描二维码时显示的文本内容</param>
		/// <param name="pixel">像素大小</param>
		/// <param name="logoPath">图标路径(例：E:\logo.jpg)</param>
		/// <returns></returns>
		public static Bitmap CreateQRCodeImage(string plainText, int pixel=10, string logoPath="")
		{
			var generator = new QRCodeGenerator();
			//QRCodeGenerator.ECCLevel：纠错级别。L（7%）、M（15%）、Q（25%）或H（30%）。说明在二维码不再可读之前，有多少二维码会被破坏
			var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
			var qrCode = new QRCode(qrCodeData);
			Bitmap bitmap;
			if (!string.IsNullOrEmpty(logoPath))
			{
				bitmap = qrCode.GetGraphic(pixel, Color.Black, Color.White, (Bitmap)Image.FromFile(logoPath));
			}
			else 
			{ 
				bitmap = qrCode.GetGraphic(pixel); 
			}
			return bitmap;
		}
	}
}
